<template>
  <div class="address-list">
    <div class="header">
      <h2>我的地址</h2>
      <button @click="handleAddClick" class="add-btn">
        添加新地址
      </button>
    </div>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading">
      <div class="loading-spinner"></div>
      正在加载地址...
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error">
      <span class="error-icon">⚠️</span>
      {{ error }}
      <button @click="retryLoading" class="retry-btn">重试</button>
    </div>

    <!-- 空状态 -->
    <div v-else-if="isEmpty" class="empty">
      <div class="empty-icon">📭</div>
      <p>暂无地址信息</p>
      <button @click="handleAddClick" class="add-btn">添加第一个地址</button>
    </div>

    <!-- 数据列表 -->
    <ul v-else class="address-items">
      <li
          v-for="address in addressList"
          :key="address.id"
          class="address-item"
      >
        <div class="address-info">
          <div class="name-phone">
            <span class="name">{{ address.name }}</span>
            <span class="phone">{{ address.phone }}</span>
            <span v-if="address.isDefault" class="default-tag">默认</span>
          </div>
          <div class="full-address">
            {{ `${address.province}${address.city}${address.district}${address.detail}` }}
          </div>
        </div>
        <div class="actions">
          <button @click="editAddress(address)" class="edit-btn">编辑</button>
          <button @click="deleteAddress(address.id)" class="delete-btn">删除</button>
          <button
              @click="setDefault(address.id)"
              class="default-btn"
              :disabled="address.isDefault"
          >
            {{ address.isDefault ? '已默认' : '设为默认' }}
          </button>
        </div>
      </li>
    </ul>

    <div v-if="showForm" class="form-overlay">
      <AddressForm
          :address="editingAddress"
          @close="handleFormClose"
          @save="handleFormSave"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, computed, nextTick} from 'vue';
import {useAddressStore} from '@/store/modules/address';
import AddressForm from './AddressForm.vue';

const addressStore = useAddressStore();
const showForm = ref(false);
const editingAddress = ref<Address | null>(null);
const isLoading = ref(true);
const error = ref<string | null>(null);

interface Address {
  id?: number;
  name: string;
  phone: string;
  province: string;
  city: string;
  district: string;
  detail: string;
  isDefault?: boolean;
}

const isEmpty = computed(() => {
  return !addressStore.addresses || addressStore.addresses.length === 0;
});

const loadAddresses = async () => {
  try {
    isLoading.value = true;
    error.value = null;
    await addressStore.fetchAddresses();
  } catch (err) {
    error.value = err instanceof Error ? err.message : '加载地址失败';
  } finally {
    isLoading.value = false;
  }
};

const retryLoading = () => {
  loadAddresses();
};

const handleAddClick = () => {
  console.log('点击添加按钮，showForm:', showForm.value);
  showForm.value = true;
  editingAddress.value = null;
  console.log('设置后showForm:', showForm.value);

  // 确保表单组件已加载
  nextTick(() => {
    console.log('nextTick后showForm:', showForm.value);
  });
};

const handleFormClose = () => {
  showForm.value = false;
};

const handleFormSave = async (addressData: Address) => {
  try {
    if (addressData.id) {
      await addressStore.updateAddress(addressData);
    } else {
      await addressStore.addAddress(addressData);
    }
    handleFormClose();
  } catch (err) {
    error.value = err instanceof Error ? err.message : '保存地址失败';
  }
};

const editAddress = (address: Address) => {
  editingAddress.value = {...address};
  showForm.value = true;
};

const deleteAddress = async (id: number) => {
  if (confirm('确定要删除这个地址吗？')) {
    try {
      // 先删除本地数据
      addressList.value = addressList.value.filter(item => item.id !== id);
      // 再同步到store
      if (import.meta.env.MODE !== 'development') {
        await addressStore.deleteAddress(id);
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '删除地址失败';
    }
  }
};

const setDefault = async (id: number) => {
  try {
    // 先更新本地数据
    addressList.value = addressList.value.map(item => ({
      ...item,
      isDefault: item.id === id
    }));
    // 再同步到store
    if (import.meta.env.MODE !== 'development') {
      await addressStore.setDefaultAddress(id);
    }
  } catch (err) {
    error.value = err instanceof Error ? err.message : '设置默认地址失败';
  }
};

const addressList = computed(() => addressStore.addresses);

onMounted(() => {
  loadAddresses();
});
</script>

<style scoped>
.address-list {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.add-btn {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.address-items {
  list-style: none;
  padding: 0;
}

.address-item {
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.error {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 4px;
  margin: 20px 0;
  color: #ff4d4f;
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
  color: #666;
}

.form-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
</style>
